//
//  myCommunityViewController.m
//  Toyohu
//
//  Created by Heige on 16/5/6.
//  Copyright © 2016年 celia. All rights reserved.
//

#import "myCommunityViewController.h"
#import "LiuXSegmentView.h"
#import "ReloadButton.h"
#import "ReloadButtonModel.h"
#import <Masonry.h>
#import "CommentAnswerTableViewCell.h"
#import "GPAFNetworking3.h"

#import "QAModel.h"
#import "TalkModel.h"
#import "TYH_LoginLoginModel.h"

#import <MJRefresh.h>

#import "TalkStyltOneTableViewCell.h"
#import "TalkStyleTwoTableViewCell.h"
#import "TalkStyleThreeTableViewCell.h"

#import "UIView+Fillet.h"
#import "QAPageViewController.h"
#define WIDTH self.view.bounds.size.width
#define HEIGHT self.view.bounds.size.height
#define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
@interface myCommunityViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
{

    UILabel *hotLabel;
    UIScrollView *_bgScrollView;
    UITableView *_leftTableView;
    UITableView *_rightTableView;
    NSMutableArray *_leftArray;
    NSMutableArray *_rightArray;
    LiuXSegmentView *view;
    NSMutableArray *idleImages;
    NSInteger leftPage;
    NSInteger rightPage;
    ReloadButton*reloadButton;
}

@end

@implementation myCommunityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    leftPage = 1;
    rightPage = 1;
    _leftArray = [NSMutableArray array];
    _rightArray = [NSMutableArray array];
    idleImages = [NSMutableArray array];
    [self getQAList];
    [self getTalk];
    for (NSUInteger i = 1; i<=17; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%lu", (unsigned long)i]];
        [idleImages addObject:image];
    }
   // self.automaticallyAdjustsScrollViewInsets = NO;
   
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
    UIView *navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH ,64)];
    navView.backgroundColor = [UIColor colorWithRed:253/255.0 green:214/255.0 blue:17/255.0 alpha:1];
    [self.view addSubview:navView];
    [self CreateView];

    view=[[LiuXSegmentView alloc] initWithFrame:CGRectMake(0, 23, WIDTH, 40) titles:@[@"问答",@"倾诉"] clickBlick:^void(NSInteger index) {
        if (index==1) {
            [_bgScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
        else
        {
            [_bgScrollView setContentOffset:CGPointMake(WIDTH, 0) animated:YES];
        }
    }];
    
    [self.view addSubview:view];
    
}

-(void)getFilter
{
    
}
-(void)CreateView
{
    _bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH , HEIGHT-110-49)];
    _bgScrollView.bounces = NO;
    _bgScrollView.delegate = self;
    _bgScrollView.pagingEnabled = YES;
    _bgScrollView.showsHorizontalScrollIndicator = NO;
    _bgScrollView.showsVerticalScrollIndicator = NO;
    _bgScrollView.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
    
    _bgScrollView.contentSize = CGSizeMake(WIDTH * 2, 0);
    [self.view addSubview:_bgScrollView];

    [_bgScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(64);
        make.bottom.equalTo(self.view).offset(0);
    }];
    
    hotLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, WIDTH/3, 40)];
    hotLabel.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
    hotLabel.textColor = [UIColor colorWithRed:128/255.0 green:128/255.0 blue:128/255.0 alpha:1];
    hotLabel.textAlignment = NSTextAlignmentNatural;
    [_bgScrollView addSubview:hotLabel];
    
    reloadButton = [[ReloadButton alloc] init];
    ReloadButtonModel*model = [ReloadButtonModel modelWithName:@"排序" icon:@"change@2x"];
    reloadButton.model = model;
    [_bgScrollView addSubview:reloadButton];
    [reloadButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.view.mas_trailing);
        make.centerY.equalTo(hotLabel.mas_centerY);
        make.width.equalTo(@80);
        make.height.equalTo(@40);
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(getFilter)];
    [reloadButton addGestureRecognizer:tap];
    
//左边TableView
    _leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, WIDTH, HEIGHT-49) style:UITableViewStylePlain];
    _leftTableView.delegate = self;
    _leftTableView.backgroundColor = RGBA(235, 234, 229, 1);
    _leftTableView.dataSource = self;
    _leftTableView.separatorColor = [UIColor clearColor];
    _leftTableView.tableHeaderView = [UIView new];
    _leftTableView.tableFooterView = [UIView new];

    [_leftTableView registerNib:[UINib nibWithNibName:@"CommentAnswerTableViewCell" bundle:nil] forCellReuseIdentifier:@"commentAns"];
    _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _leftTableView.showsVerticalScrollIndicator = NO;
    
    [_bgScrollView addSubview:_leftTableView];
    
    MJRefreshGifHeader *leftheader = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadleftTableViewNewData)];
    // 设置普通状态的动画图片
    [leftheader setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
    [leftheader setImages:idleImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    [leftheader setImages:idleImages forState:MJRefreshStateRefreshing];
    // 设置header
    _leftTableView.mj_header = leftheader;
    leftheader.lastUpdatedTimeLabel.hidden = YES;
    leftheader.stateLabel.hidden = YES;
    leftheader.ignoredScrollViewContentInsetTop = - 5;
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(leftloadMoreData)];
    // 设置刷新图片
    [footer setImages:idleImages forState:MJRefreshStateRefreshing];
    footer.refreshingTitleHidden = YES;
    footer.stateLabel.hidden = YES;
    // 设置尾部
    _leftTableView.mj_footer = footer;
    
    
    
//右边TableView
    _rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH, 0, WIDTH, HEIGHT-49) style:UITableViewStylePlain];
    _rightTableView.delegate = self;
    _rightTableView.backgroundColor = RGBA(235, 234, 229, 1);
    
    _rightTableView.dataSource = self;
    _rightTableView.separatorColor = [UIColor clearColor];
    _rightTableView.tableHeaderView = [UIView new];
    _rightTableView.tableFooterView = [UIView new];
    [_rightTableView registerNib:[UINib nibWithNibName:@"TalkStyltOneTableViewCell" bundle:nil] forCellReuseIdentifier:@"talkone"];
    [_rightTableView registerNib:[UINib nibWithNibName:@"TalkStyleTwoTableViewCell" bundle:nil] forCellReuseIdentifier:@"talktwo"];
    [_rightTableView registerNib:[UINib nibWithNibName:@"TalkStyleThreeTableViewCell" bundle:nil] forCellReuseIdentifier:@"talkthree"];
    _rightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _rightTableView.showsVerticalScrollIndicator = NO;
    
    [_bgScrollView addSubview:_rightTableView];
    
    MJRefreshGifHeader *rightheader = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadrightTableViewNewData)];
    // 设置普通状态的动画图片
    [rightheader setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
    [rightheader setImages:idleImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    [rightheader setImages:idleImages forState:MJRefreshStateRefreshing];
    // 设置header
    _leftTableView.mj_header = rightheader;
    rightheader.lastUpdatedTimeLabel.hidden = YES;
    rightheader.stateLabel.hidden = YES;
    rightheader.ignoredScrollViewContentInsetTop = - 5;
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *rightfooter = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(rightloadMoreData)];
    // 设置刷新图片
    [rightfooter setImages:idleImages forState:MJRefreshStateRefreshing];
    // 设置尾部
    _rightTableView.mj_footer = rightfooter;
    
    
}

-(void)getQAList
{
    [GPAFNetworking3 get:[NSString stringWithFormat:@"%@?order=hot&source=toyohuApp&site=QA&page=%ld",GetCommunityList,(long)leftPage] progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(id  _Nonnull responseObject) {
        
        TYH_LoginLoginModel *myModel = [[TYH_LoginLoginModel alloc] initWithDictionary:responseObject];
        if (myModel.code!=1) {
            SHOW_ERROR
        }
        else
        {
            [_leftArray removeAllObjects];
            for (NSDictionary *dict in responseObject[@"msg"]) {
                QAModel*model = [[QAModel alloc]init];
                model.caCommentNum = [dict[@"caCommentNum"]integerValue];
                model.caContent = dict[@"caContent"];
                model.caFavNum = [dict[@"caFavNum"]integerValue];
                model.caId = [dict[@"caId"]integerValue];
                model.caPraiseNum = [dict[@"caPraiseNum"]integerValue];
                model.caTitle = dict[@"caTitle"];
                [_leftArray addObject:model];
                [_leftTableView.mj_footer endRefreshing];
                [_leftTableView reloadData];
            }
        }
        
    } failure:^(NSString * _Nonnull errorLD) {
        leftPage--;
        [_leftTableView.mj_footer endRefreshing];
        SHOW_NTERROR
    }];
}


-(void)getTalk
{
    [GPAFNetworking3 get:[NSString stringWithFormat:@"%@?order=hot&source=toyohuApp&site=talk&page=%ld",GetCommunityList,(long)rightPage] progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(id  _Nonnull responseObject) {
        TYH_LoginLoginModel *myModel = [[TYH_LoginLoginModel alloc] initWithDictionary:responseObject];
        if (myModel.code!=1) {
            SHOW_ERROR
        }
        else
        {
            [_rightArray removeAllObjects];
            for (NSDictionary*dict in responseObject[@"msg"]) {
                TalkModel*model = [[TalkModel alloc]init];
                model.caId = [dict[@"caId"]integerValue];
                model.pId = dict[@"pId"];
                model.caTitle = dict[@"caTitle"];
                model.caContent = dict[@"caContent"];
                model.caVoice = dict[@"caVoice"];
                model.caCommentNum = [dict[@"caCommentNum"]integerValue];
                model.caViewNum = [dict[@"caViewNum"]integerValue];
                model.caFavNum = [dict[@"caFavNum"]integerValue];
                model.caTime = dict[@"caTime"];
                
                model.username = dict[@"Parent"][@"username"];
                model.pHeadUrl = dict[@"Parent"][@"pHeadUrl"];
              
                [_rightArray addObject:model];
                [_rightTableView.mj_footer endRefreshing];
                [_rightTableView reloadData];
                hotLabel.text = [NSString stringWithFormat:@"全部(%lu)",(unsigned long)_rightArray.count];
            }
        }
    } failure:^(NSString * _Nonnull errorLD) {
        rightPage--;
        SHOW_NTERROR
    }];
}
-(void)loadleftTableViewNewData
{
    [self getQAList];
    [_leftTableView reloadData];
    [_leftTableView.mj_header endRefreshing];
}

-(void)leftloadMoreData
{
    leftPage++;
    [self getQAList];
    [_leftTableView reloadData];
    
}
-(void)loadrightTableViewNewData
{
    [self getTalk];
    [_rightTableView reloadData];
    [_rightTableView.mj_header endRefreshing];
}
-(void)rightloadMoreData
{
    rightPage++;
    [self getTalk];
    [_rightTableView reloadData];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView==_leftTableView) {
        return 1;
    }
    else if (tableView==_rightTableView)
    {
        return 3;
    }
    return 0;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _leftTableView)
    {
            return _leftArray.count;
    }
    else if (tableView==_rightTableView)
    {
        if (section==0) {
            return _rightArray.count;
        }
        else if (section==1)
        {
            return _rightArray.count;
        }
        else{
            return _rightArray.count;
        }
    }
        return 0;
   
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _leftTableView)
    {

            _leftTableView.rowHeight = 116;
            CommentAnswerTableViewCell*cell =[tableView dequeueReusableCellWithIdentifier:@"commentAns" forIndexPath:indexPath];
                    if (!cell) {
                        cell = (CommentAnswerTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: @"commentAns"];
                    }
        
            [cell.tags filletWithcornerRadius:cell.tags.frame.size.height/2];
            cell.tags.textAlignment = NSTextAlignmentCenter;
            cell.tags.backgroundColor = [UIColor colorWithRed:31/255.0 green:226/255.0 blue:197/255.0 alpha:1];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.model = _leftArray[indexPath.row];
            return cell;


    }
    else if (tableView==_rightTableView)
    {
        if (indexPath.section==0) {
            _rightTableView.rowHeight = 180;
            TalkStyltOneTableViewCell*cell =[tableView dequeueReusableCellWithIdentifier:@"talkone" forIndexPath:indexPath];
            if (!cell) {
                cell = (TalkStyltOneTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: @"talkone"];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.model = _rightArray[indexPath.row];
            return cell;
        }
        else if (indexPath.section==1)
        {
            _rightTableView.rowHeight = 180;
            TalkStyleTwoTableViewCell*cell =[tableView dequeueReusableCellWithIdentifier:@"talktwo" forIndexPath:indexPath];
            if (!cell) {
                cell = (TalkStyleTwoTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: @"talktwo"];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.model = _rightArray[indexPath.row];
            return cell;
        }
        else
        {
            _rightTableView.rowHeight = 180;
            TalkStyleThreeTableViewCell*cell =[tableView dequeueReusableCellWithIdentifier:@"talkthree" forIndexPath:indexPath];
            if (!cell) {
                cell = (TalkStyleThreeTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: @"talkthree"];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.model = _rightArray[indexPath.row];
            return cell;
        }
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==_leftTableView) {
        QAPageViewController*VC = [[QAPageViewController alloc]init];
        QAModel *model = _leftArray[indexPath.row];
        VC.caId = model.caId;
        [self.navigationController pushViewController:VC animated:YES];
    }
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
}


@end
